package com.diyunapp.xilinapp.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.RecycleViewBuyCarAdapter;
import com.diyunapp.xilinapp.bean.BuyCarGoodsInBean;
import com.diyunapp.xilinapp.bean.BuyCarGoodsOutBean;
import com.diyunapp.xilinapp.bean.ParamsBean;
import com.diyunapp.xilinapp.details.GoodsDetailActivity;
import com.diyunapp.xilinapp.details.OrderConfirmActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.BuyCarGoodsInfoChageInterface;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/24.
 */
public class BuyCarFragment extends Fragment implements View.OnClickListener {

    @Bind(R.id.edit_buycar_tv)
    TextView editBuycarTv;
    @Bind(R.id.buycar_recylerView)
    RecyclerView buycarRecylerView;
    @Bind(R.id.buycar_swiperefreshlayout)
    SwipeRefreshLayout buycarSwiperefreshlayout;
    @Bind(R.id.buycar_buyall_cb)
    CheckBox buycarBuyallCb;
    @Bind(R.id.buycar_total_price_tv)
    TextView buycarTotalPriceTv;
    @Bind(R.id.commit_buycar_tv)
    TextView commitBuycarTv;
    @Bind(R.id.buycar_buyall_ll)
    LinearLayout buycarBuyallLl;

    private View myFragmentView;
    private LinearLayoutManager outListManager;
    private List<BuyCarGoodsOutBean> outList;
    private RecycleViewBuyCarAdapter outAdapter;

    private float total_price = 0;
    private boolean ifDeletestate = false;

    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";

    private String query_error;
    private boolean selectAllonlyUI = false;
    private String deleteId;

    private Dialog deleteDialog;
    private TextView confirm_bt;
    private TextView cancel_bt;

    private boolean ifSelectAll = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        myFragmentView = inflater.inflate(R.layout.fragment_buycar, null);
        ButterKnife.bind(this, myFragmentView);
        initViews();
        if(MainActivity.myLogin.isLoginState())
        {
            loginKey = MainActivity.myLogin.getLoginkey();
            getBuyCarGoods();
        }
        else
        {
            Toast.makeText(getActivity(),"您还没有登录！",Toast.LENGTH_SHORT).show();
        }
        return myFragmentView;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden)
        {
            if(MainActivity.myLogin.isLoginState())
            {
                loginKey = MainActivity.myLogin.getLoginkey();
                if(buycarBuyallCb.isChecked())
                {
                    selectAllonlyUI = true;
                    buycarBuyallCb.setChecked(false);
                }
                getBuyCarGoods();
            }
            else
            {
                outList.clear();
                outAdapter.notifyDataSetChanged();
                Toast.makeText(getActivity(),"您还没有登录！",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initViews() {
        outListManager = new LinearLayoutManager(getActivity());
        outList = new ArrayList<>();
        outAdapter = new RecycleViewBuyCarAdapter(outList, getActivity(), new BuyCarGoodsInfoChageInterface() {
            @Override
            public void changeGoodsNum(int doType, int num) {
                Log.i("zhangxiaoxidebug","BuyCarFragment doType= "+doType);
                switch (doType) {
                    //选中商店
                    case 1:
                        if (isAllStoreSelected()) {
                            Log.i("zhangxiaoxidebug","buycarBuyallCb state= "+buycarBuyallCb.isChecked());
                            if(!buycarBuyallCb.isChecked())
                            {
                                selectAllonlyUI = true;
                                buycarBuyallCb.setChecked(true);
                            }
                        }
                        getTotalprice();
                        break;
                    //取消选中商店
                    case 2:
                        //当全选状态由选中进入未选中时
                        if(buycarBuyallCb.isChecked())
                        {
                            selectAllonlyUI = true;
                            buycarBuyallCb.setChecked(false);
                        }
                        getTotalprice();
                        break;
                    //商品数量修改
                    case 3:
                        //如果收到此消息，说明当前商品处于选中状态，需要更新总金额
                        getTotalprice();
                        break;
                    //商品数量修改
                    case 4:
                        //删除商品
                        deleteDialog.show();
                        deleteId = String.valueOf(num);
                        break;
                    case 5:
                        //查看商品详情
                        Intent likeInt = new Intent(getActivity(), GoodsDetailActivity.class);
                        likeInt.putExtra("GoodId",String.valueOf(num));
                        startActivity(likeInt);
                        break;
                    default:
                        break;
                }
            }
        });
        buycarRecylerView.setLayoutManager(outListManager);
        buycarRecylerView.setAdapter(outAdapter);

        buycarSwiperefreshlayout.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        buycarSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "invoke onRefresh...");
                if(MainActivity.myLogin.isLoginState())
                {
                    if (buycarBuyallCb.isChecked()) {
                        selectAllonlyUI = true;
                        buycarBuyallCb.setChecked(false);
                    }
                    getBuyCarGoods();
                }
                else
                {
                    Toast.makeText(getActivity(),"您还没有登录！",Toast.LENGTH_SHORT).show();
                    buycarSwiperefreshlayout.setRefreshing(false);
                }
            }
        });

        //提交订单的全选功能
        buycarBuyallCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //onlyUI为true,说明checkbox的状态改变是由内部点击事件逐层处理得来的
                Log.i("zhangxiaoxidebug","selectAllonlyUI= "+selectAllonlyUI);
                ifSelectAll = isChecked;
                if (selectAllonlyUI)
                {
                    selectAllonlyUI = false;
                }
                else
                {
                    for (int i = 0; i < outList.size(); i++) {
                        outList.get(i).setStoreSelected(isChecked);
                    }
                    outAdapter.notifyDataSetChanged();

                    if (isChecked) {
                        getFinalTotalprice();
                        buycarTotalPriceTv.setText("合计：￥" + total_price);
                    } else {
                        total_price = 0;
                        buycarTotalPriceTv.setText("合计：￥" + total_price);
                    }
                }
            }
        });

        editBuycarTv.setOnClickListener(this);
        commitBuycarTv.setOnClickListener(this);

        //各类操作提示对话框相关功能处理
        View setView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_two_button, null);
        confirm_bt = (TextView)setView.findViewById(R.id.confirm_button_tv);
        confirm_bt.setOnClickListener(this);
        cancel_bt = (TextView)setView.findViewById(R.id.cancel_button_tv);
        cancel_bt.setOnClickListener(this);
        deleteDialog = new Dialog(getActivity(), R.style.userinfo_dailog_style);
        deleteDialog.setContentView(setView);
        deleteDialog.setCanceledOnTouchOutside(false);
    }

    private void getTotalprice() {
        total_price = 0;
        for (int i = 0; i < outList.size(); i++) {
            total_price += outList.get(i).getTotalPrice();
        }
        buycarTotalPriceTv.setText("合计：￥" + total_price);
    }

    private void getFinalTotalprice() {
        total_price = 0;
        for (int i = 0; i < outList.size(); i++) {
            total_price += outList.get(i).getTotalOutPrice();
        }
        buycarTotalPriceTv.setText("合计：￥" + total_price);
    }
    private boolean isAllStoreSelected() {
        boolean flag = true;
        for (int i = 0; i < outList.size(); i++) {
            if (!outList.get(i).isStoreSelected()) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    @Override
    public void onClick(View v) {

        if(!MainActivity.myLogin.isLoginState())
        {
            Toast.makeText(getActivity(),"您还没有登录！",Toast.LENGTH_SHORT).show();
            return;
        }

        switch (v.getId()) {
            case R.id.edit_buycar_tv:
                if (ifDeletestate) {
                    ifDeletestate = false;
                    getBuyCarGoods();
                    buycarBuyallLl.setVisibility(View.VISIBLE);
                    editBuycarTv.setText("编辑");
                } else {
                    if (outList.size() > 0) {
                        ifDeletestate = true;
                        getBuyCarGoods();
                        buycarBuyallLl.setVisibility(View.GONE);
                        editBuycarTv.setText("完成");
                    }
                    else {
                        Toast.makeText(getActivity(),"没有可编辑的商品！",Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.commit_buycar_tv:
                //获取商品参数
                int selected = 0;
                StringBuffer params = new StringBuffer();
                for (int i = 0; i < outList.size(); i++) {
                    for (int j = 0; j < outList.get(i).getGoodsList().size(); j++) {
                        BuyCarGoodsInBean theGood = outList.get(i).getGoodsList().get(j);
                        //安卓问题导致某商品因上线滚动而不在当前页面内时，商品选中状态不被设置，故加上全选时的特殊处理
                        if (theGood.isGoodSelected() || ifSelectAll) {
                            String cardID = theGood.getCart_id();
                            int num = theGood.getTotalGoodNum();
                            params.append(cardID + "|" + num);
                            params.append(",");
                            selected ++;
                        }
                    }
                }

                if(selected>0)
                {
                    params.deleteCharAt(params.length() - 1);
                    Log.i("zhangxiaoxidebug", "params=" + params.toString());
                    Intent buyInt = new Intent(getActivity(), OrderConfirmActivity.class);
                    buyInt.putExtra("CardId", params.toString());
                    buyInt.putExtra("IfCart", "1");
                    startActivityForResult(buyInt,1);
                }
                else
                {
                    Toast.makeText(getActivity(),"请选择需要结算的商品！",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.confirm_button_tv:
                deleteDialog.dismiss();
                deleteCars(deleteId);
                break;
            case R.id.cancel_button_tv:
                deleteDialog.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void getBuyCarGoods() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_cart&op=cart_list&key=" + loginKey;
        Log.i("zhangxiaoxidebug", "url =" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        buycarSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 2:
                                Toast.makeText(getActivity(), query_error, Toast.LENGTH_LONG).show();
                                break;
                            case 0:
                                Toast.makeText(getActivity(), "参数缺失，获取失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {
                        buycarSwiperefreshlayout.setRefreshing(true);
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "buycar_result=" + result);
                        //使用店铺的id作为key,在outlist中的position作为值，用于将商品按店铺分类组合
                        HashMap<String, Integer> storeMap = new HashMap<String, Integer>();
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            String datasStr = jsObjectCode.getString("datas");
                            JSONObject jsObjectDatas = new JSONObject(datasStr);
                            if (datasStr.contains("cart_list")) {

                            } else {
                                query_error = jsObjectDatas.getString("error");
                                return 2;
                            }

                            outList.clear();
                            JSONArray jsArrayCartList = jsObjectDatas.getJSONArray("cart_list");
                            for (int i = 0, storeNum = 0; i < jsArrayCartList.length(); i++) {
                                JSONObject jsObjectGood = jsArrayCartList.getJSONObject(i);
                                String cart_id = jsObjectGood.getString("cart_id");
                                String buyer_id = jsObjectGood.getString("buyer_id");
                                String store_id = jsObjectGood.getString("store_id");
                                String store_name = jsObjectGood.getString("store_name");
                                String goods_id = jsObjectGood.getString("goods_id");
                                String goods_name = jsObjectGood.getString("goods_name");
                                String goods_price = jsObjectGood.getString("goods_price");
                                String market_price = goods_price;
                                if(jsObjectGood.has("goods_marketprice"))
                                {
                                    market_price = jsObjectGood.getString("goods_marketprice");
                                }

                                String goods_params = "";
                                if(jsObjectGood.has("goods_spec"))
                                {
                                    goods_params = jsObjectGood.getString("goods_spec");
                                }
                                StringBuffer paramsBuffer = new StringBuffer("");
                                if (goods_params == null || goods_params.isEmpty() || goods_params.equals("null")) {
                                } else {
                                    List<ParamsBean> goodsParamsList = FormatConfirm.getParameters(goods_params);

                                    for (int j = 0; j < goodsParamsList.size(); j++) {
                                        paramsBuffer.append(goodsParamsList.get(j).getParamsKey());
                                        paramsBuffer.append("  ");
                                        Log.i("zhangxiaoxidebug", "resultinfo11222=" + paramsBuffer.toString());
                                    }
                                }
                                String goods_num = jsObjectGood.getString("goods_num");
                                String bl_id = jsObjectGood.getString("bl_id");
                                String goods_image_url = jsObjectGood.getString("goods_image_url");
                                String goods_sum = jsObjectGood.getString("goods_sum");
                                BuyCarGoodsInBean tempGood = new BuyCarGoodsInBean(cart_id, goods_id, goods_name, goods_image_url, goods_price, market_price, paramsBuffer.toString(), FormatConfirm.stringToInt(goods_num), false,ifDeletestate);

                                if (storeMap.containsKey(store_id)) {
                                    outList.get(storeMap.get(store_id)).getGoodsList().add(tempGood);
                                } else {
                                    outList.add(new BuyCarGoodsOutBean(store_id, buyer_id, store_name, false));
                                    outList.get(storeNum).getGoodsList().add(tempGood);
                                    storeMap.put(store_id, storeNum);
                                    storeNum++;
                                }
                            }

                            Log.i("zhangxiaoxidebug", "outList lenth = " + outList.size());
                            Log.i("zhangxiaoxidebug", "before notifyDataSetChanged----------");
                            outAdapter.notifyDataSetChanged();
                            Log.i("zhangxiaoxidebug", "notifyDataSetChanged end 11111 ");

                            total_price = 0;
                            buycarTotalPriceTv.setText("合计：￥" + total_price);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        buycarSwiperefreshlayout.setRefreshing(false);
                        Toast.makeText(getActivity(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void deleteCars(String carid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_cart&op=cart_del";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("cart_id", carid);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getActivity(), "购物车删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            } else {
                                String datas = jsObjectCode.getString("datas");
                                if (datas.equals("1")) {
                                    Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_LONG).show();
                                    getBuyCarGoods();
                                } else {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getActivity(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getActivity(), "购物车删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(MainActivity.myLogin.isLoginState())
        {
            if (buycarBuyallCb.isChecked()) {
                selectAllonlyUI = true;
                buycarBuyallCb.setChecked(false);
            }
            getBuyCarGoods();
        }
        else
        {
            Toast.makeText(getActivity(),"您还没有登录！",Toast.LENGTH_SHORT).show();
            buycarSwiperefreshlayout.setRefreshing(false);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
